package com.link.play.fit.ai.ui.view

import android.animation.ObjectAnimator
import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
import android.view.animation.LinearInterpolator
import com.link.play.fit.ai.R

class LoadingStripView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {

    // 背景色和光点色
    private var bgColor = Color.LTGRAY
    private var dotColor = Color.WHITE
    private val dotRadius = 4.dpToPx() // 光点半径
    private val animationDuration = 1000L // 动画周期

    // 光点位置偏移量（通过动画修改）
    private var dotOffset = 0f
        set(value) {
            field = value
            invalidate() // 触发重绘
        }

    init {
        // 从 XML 属性读取颜色（可选）
        context.theme.obtainStyledAttributes(attrs, R.styleable.LoadingStripView, 0, 0).apply {
            try {
                bgColor = getColor(R.styleable.LoadingStripView_bgColor, Color.LTGRAY)
                dotColor = getColor(R.styleable.LoadingStripView_dotColor, Color.WHITE)
            } finally {
                recycle()
            }
        }

        // 启动无限动画
        startAnimation()
    }

    private fun startAnimation() {
        val animator = ObjectAnimator.ofFloat(this, "dotOffset", 0f, 1f).apply {
            duration = animationDuration
            repeatCount = ValueAnimator.INFINITE
            repeatMode = ValueAnimator.REVERSE // 来回运动
            interpolator = LinearInterpolator()
        }
        animator.start()
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        // 绘制背景长条
        canvas.drawColor(bgColor)

        // 计算光点位置（根据 dotOffset 0~1 映射到左右边界）
        val dotX = paddingStart + (width - paddingStart - paddingEnd - 2 * dotRadius) * dotOffset
        val dotY = height / 2f

        // 绘制白色光点
        canvas.drawCircle(dotX + dotRadius, dotY, dotRadius, Paint().apply {
            color = dotColor
            isAntiAlias = true
        })
    }

    // 停止动画（可选）
    fun stopAnimation() {
        clearAnimation()
    }

    // DP 转像素
    private fun Int.dpToPx(): Float = this * resources.displayMetrics.density
}